'use client'

import { useState } from 'react'
import { Form, Input, Button, Card, Typography, message, Row, Col, Divider } from 'antd'
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { request } from '@/utils/request'
import { API_ENDPOINTS, USER_TYPES } from '@/utils/constants'

const { Title, Text } = Typography

interface RegisterForm {
  username: string
  email: string
  password: string
  confirmPassword: string
  phone?: string
  realName?: string
  userType: 'INDIVIDUAL' | 'ENTERPRISE'
  companyName?: string
  address?: string
}

export default function RegisterPage() {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [userType, setUserType] = useState<'INDIVIDUAL' | 'ENTERPRISE'>('INDIVIDUAL')
  const router = useRouter()

  const onFinish = async (values: RegisterForm) => {
    setLoading(true)
    try {
      const response = await request.post(API_ENDPOINTS.AUTH.REGISTER, {
        ...values,
        userType
      })

      if (response.code === 200) {
        message.success('注册成功！请登录')
        router.push('/login')
      } else {
        message.error(response.message || '注册失败')
      }
    } catch (error: any) {
      message.error(error.message || '网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px'
    }}>
      <Card style={{ width: '100%', maxWidth: '500px', boxShadow: '0 8px 24px rgba(0,0,0,0.12)' }}>
        <div style={{ textAlign: 'center', marginBottom: '30px' }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: '8px' }}>
            注册账号
          </Title>
          <Text type="secondary">
            加入高端海产品交易平台
          </Text>
        </div>

        {/* User Type Selection */}
        <Row gutter={16} style={{ marginBottom: '20px' }}>
          <Col span={12}>
            <Button 
              block 
              type={userType === 'INDIVIDUAL' ? 'primary' : 'default'}
              onClick={() => setUserType('INDIVIDUAL')}
            >
              个人用户
            </Button>
          </Col>
          <Col span={12}>
            <Button 
              block 
              type={userType === 'ENTERPRISE' ? 'primary' : 'default'}
              onClick={() => setUserType('ENTERPRISE')}
            >
              企业用户
            </Button>
          </Col>
        </Row>

        <Form
          form={form}
          name="register"
          onFinish={onFinish}
          layout="vertical"
          requiredMark={false}
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3个字符' },
              { max: 50, message: '用户名最多50个字符' }
            ]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名" 
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input 
              prefix={<MailOutlined />} 
              placeholder="邮箱地址" 
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="phone"
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input 
              prefix={<PhoneOutlined />} 
              placeholder="手机号码 (可选)" 
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="realName"
            rules={[
              { max: 50, message: '姓名最多50个字符' }
            ]}
          >
            <Input 
              placeholder="真实姓名 (可选)" 
              size="large"
            />
          </Form.Item>

          {userType === 'ENTERPRISE' && (
            <Form.Item
              name="companyName"
              rules={[
                { required: true, message: '请输入公司名称' },
                { max: 100, message: '公司名称最多100个字符' }
              ]}
            >
              <Input 
                placeholder="公司名称" 
                size="large"
              />
            </Form.Item>
          )}

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6个字符' },
              { max: 20, message: '密码最多20个字符' }
            ]}
          >
            <Input.Password 
              prefix={<LockOutlined />} 
              placeholder="密码" 
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                },
              }),
            ]}
          >
            <Input.Password 
              prefix={<LockOutlined />} 
              placeholder="确认密码" 
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              size="large" 
              block 
              loading={loading}
            >
              注册
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        <div style={{ textAlign: 'center' }}>
          <Text type="secondary">
            已有账号？ 
            <Link href="/login" style={{ marginLeft: '8px' }}>
              立即登录
            </Link>
          </Text>
        </div>
      </Card>
    </div>
  )
}